package tracker;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import models.Notification;
import models.PunchTime;
import models.TimeUser;
import models.TimeUtils;
import models.Workday;
import models.Workday.WorkdayType;

public class NotificationGenerator {

	public static void cleanupNotifications() {

	}

	public static void generateNotifications() {
		List<TimeUser> allUsers = TimeUser.all().fetch();
		Iterator it = allUsers.iterator();
		while (it.hasNext()) {
			TimeUser user = (TimeUser) it.next();
			List<PunchTime> points = user.findPointsForDay(Calendar
					.getInstance().getTime());

			createNotificationForWorkday(createWorkdayForUser(user, points));
		}
	}

	private static Workday createWorkdayForUser(TimeUser user,
			List<PunchTime> points) {
		Workday wkday = new Workday();
		wkday.owner = user;

		if (points.size() > 0) {
			wkday.startTime = points.get(0).timeStamp;
			// test for forgetfullness
			if (points.size() % 2 != 0) {
				// did the user forgot , or just signed out as something else.
				wkday.dayType = user.lastWorkType == WorkdayType.NORMAL ? Workday.WorkdayType.FORGOT
						: user.lastWorkType;
			} else {
				wkday.endTime = points.remove(points.size() - 1).timeStamp;
				wkday.dayType = user.lastWorkType;
			}

			wkday.totalWorkDuration = calculateWorkHours(points);
		} else {
			if (user.lastWorkType != WorkdayType.NORMAL) {
				wkday.dayType = user.lastWorkType;
			} else {
				wkday.dayType = WorkdayType.ABSENT;
			}
			wkday.totalWorkDuration = 0L;
		}

		wkday.save();
		return wkday;
		// remove the last
	}

	private static Long calculateWorkHours(List<PunchTime> points) {
		Long totalSeconds = 0L;
		if (points.size() > 1) {
			for (Iterator iterator = points.iterator(); iterator.hasNext();) {
				try {
					PunchTime fTime = (PunchTime) iterator.next();
					PunchTime sTime = (PunchTime) iterator.next();

					totalSeconds += TimeUtils.secondsBetween(fTime.timeStamp,
							sTime.timeStamp);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					return 0L;
				}
			}

			return totalSeconds;
		}

		return 0L;
	}

	private static void createNotificationForWorkday(Workday wkday) {
		if (wkday.dayType == Workday.WorkdayType.NORMAL)
			return;

		Notification notification = new Notification();
		if (wkday.dayType == Workday.WorkdayType.FORGOT) {
			notification.owner = wkday.owner;
			notification.message = "You forgot to sign out";
			notification.save();
		}
	}
}
